#!/bin/bash
# ============================================================
# Script Name:    toolsBringup.sh
# Description:    启动AGV系统辅助工具脚本
#                 包括进程监控等后台维护工具
# Author:         haibo
# Created Date:   2025-07-24
# Version:        1.0
# Modified Date:  2025-09-09
# Modified By:    haibo
# Modification:   初始版本
# Usage:          ./toolsBringup.sh [日志文件路径]
# Notes:          1. 所有工具脚本位于${HOME}/lgimRobot/tools目录
#                 2. 支持自定义工具脚本列表
#                 3. 需要common.sh公共函数库支持
# ============================================================
source ${HOME}/lgimRobot/bin/common "$@"
TOOL_DIR="${HOME}/lgimRobot/tools/run"
PID_FILE="/tmp/process.pid"

main() {
    # 检查目录是否存在
    if [ ! -d "$TOOL_DIR" ]; then
        log "ERROR" "目录 $TOOL_DIR 不存在"
        return 1
    fi

    executables=$(find "$TOOL_DIR" -maxdepth 1 -type f -executable | sort)

    if [ -z "$executables" ]; then
        log "INFO" "未找到可执行文件"
        return 0
    fi

    # 顺序执行文件
    for exe in $executables; do
        log "INFO" "正在执行: $exe"
        
        # 启动可执行文件
        "$exe" > /dev/null 2>&1 &
        local exit_code=$?
        local pid=$!
        
        # 检查启动是否成功
        if [ $exit_code -ne 0 ]; then
            log "ERROR" "$exe 启动失败 (退出码: $exit_code)"
            return $exit_code
        fi
        
        # 将 PID 写入文件
        echo "$pid" >> "$PID_FILE"
        log "INFO" "$exe 已启动 : PID $pid"
        
        # 检查进程是否仍在运行
        if ! ps -p $pid > /dev/null; then
            log "ERROR" "$exe 启动后立即退出 (PID: $pid)"
            return 1
        fi
    done

    log "INFO" "所有可执行文件已成功启动"
    return 0
}

# 执行主函数并处理退出状态
if main; then
    exit 0
else
    exit_code=$?
    log "ERROR" "脚本执行失败 (退出码: $exit_code)"
    exit $exit_code
fi
